package cn.tnar.yunpark.huasai.nbiot;

import cn.tnar.yunpark.huasai.CRC16;
import cn.tnar.yunpark.util.DateTimeUtil;
import cn.tnar.yunpark.util.Util;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.time.LocalDateTime;

/**
 * Created by tieh on 2017/6/22.
 */
public class HuasaiNbiotAck {
    private int stopNo;
    private LocalDateTime time;

    public HuasaiNbiotAck(int stopNo) {
        this.stopNo = stopNo;
        time = LocalDateTime.now();
    }

    public void setTime(LocalDateTime time) {
        this.time = time;
    }

    public byte[] encode() {
        byte[] bs = new byte[19];
        ByteBuf buf = Unpooled.wrappedBuffer(bs).writerIndex(0).readerIndex(0);
        buf.writeByte(0x77);
        buf.writeShort(0x70);
        buf.writeShort(stopNo);
        buf.writeByte(0);
        buf.writeInt(0);
        buf.writeBytes(Util.hexToBytes(DateTimeUtil.formatBasic(time)));   // BCD格式日期

        int crc = CRC16.calc(bs, 0, bs.length - 2);
        buf.writeShort(crc);

        return bs;
    }
}
